import axios from 'axios'
import qs from 'qs'

// create an axios instancenpm install --save axios vue-axios
const http = axios.create({
  baseURL: 'http://localhost:8092/', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 1000 * 120, // request timeout
  withCredentials: true
})

// request interceptor
http.interceptors.request.use(
  request => {
    if (request.method === 'post') {
      request.data = qs.stringify(request.data)
      request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    }
    const token = sessionStorage.getItem('token')
    if (token) {
      console.log(token)
      request.headers.Authorization = token
    }

    return request
  }
)

// response interceptor
http.interceptors.response.use(
  response => {
    return response.data
  }
)

export default http
